where 泛型類型條件約束


Posted by nimblefrog on 2021-01-04

泛型定義中的 where 子句(where T)指定型別T的條件約束,以用來作為泛型型別、方法、委派或本機函式中型別參數的引數。
條件約束可以指定

  1. 介面
    public class AGenericClass<T> where T : IComparable<T> { }
    
  2. 基類
    public class UsingEnum<T> where T : System.Enum { }
    public class UsingDelegate<T> where T : System.Delegate { }
    public class Multicaster<T> where T : System.MulticastDelegate { }
    
  3. 要求泛型型別作為參考(class)、值(notnullstruct)或非受控型別(unmanaged )
  4. new 條件約束: 指定泛型類別宣告中的型別引數都必須有公用無參數建構函式,若要使用 new 條件約束,型別不能為抽象
    class ItemFactory<T> where T : new()
    {
         public T GetNewItem()
         {
             return new T();
         }
    }
    

where (泛型類型條件約束) (C# 參考)
new 條件約束 (C# 參考)










Related Posts

【隨堂筆記】套件模組與環境設定

【隨堂筆記】套件模組與環境設定

簡明人月神話:專案管理之道(The Mythical Man-Month)導讀書摘

簡明人月神話:專案管理之道(The Mythical Man-Month)導讀書摘

[day-3]布林、undefined、null/字串數字轉換/比較與邏輯運算子

[day-3]布林、undefined、null/字串數字轉換/比較與邏輯運算子


Comments